using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.WebPartPages;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Xml;
using SP_Form_Suggestion;

namespace SP_Form_Suggestion.Features.Config_List_Feature
{


    [Guid("097a6761-f5a2-4fe1-a9e7-d675ac134382")]
    public class Feature1EventReceiver : SPFeatureReceiver
    {

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWeb web = properties.Feature.Parent as SPWeb;
            createConfigList(web);

            // Set default Configs
            web.SetProperty(CONST.PROPERTY_BAG_JQUERY_UI_CSS_URL, CONST.JQUERY_UI_CSS_URL);
            web.SetProperty(CONST.PROPERTY_BAG_JQUERY_UI_URL, CONST.JQUERY_UI_URL);
            web.SetProperty(CONST.PROPERTY_BAG_JQUERY_URL, CONST.JQUERY_URL);
            web.Update();
        }

        private SPList createConfigList(SPWeb web)
        {
            SPList list;

            // already existing
            try
            {
                list = web.Lists[CONST.CONFIG_LIST_NAME];
            }
            catch (Exception ex)
            {
                list = null;
            }
            if (null != list)
                return list;
            // New list
            Guid listGuid = web.Lists.Add(CONST.CONFIG_LIST_NAME, "", SPListTemplateType.GenericList);

            web.Update();
            list = web.Lists[listGuid];


            list.Fields.Add(CONST.TARGET_FIELD_NAME, SPFieldType.Text, true);
            list.Fields.Add(CONST.TARGET_LIST_GUID, SPFieldType.Text, true);
            list.Fields.Add(CONST.TARGET_LIST_NAME, SPFieldType.Text, true);

            list.Fields.Add(CONST.SOURCE_LIST_URL, SPFieldType.Text, true);
            list.Fields.Add(CONST.SOURCE_FIELD_NAME_INTERNAL, SPFieldType.Text, true);
            list.Fields.Add(CONST.SOURCE_WEB_URL, SPFieldType.Text, false);
            list.Fields.Add(CONST.SOURCE_LIST_GUID, SPFieldType.Text, false);

            list.Fields.Add(CONST.USE_AJAX_PROXY, SPFieldType.Boolean, false);

            list.Update();
            #region Field details
            if (list.Fields.ContainsField(CONST.USE_AJAX_PROXY))
            {
                SPFieldBoolean sourceField = list.Fields.GetField(CONST.USE_AJAX_PROXY) as SPFieldBoolean;
                sourceField.Description = "(Use the \"Ajax Proxy\" for cross domain access.)";
                sourceField.Update();

            }
            if (list.Fields.ContainsField(CONST.SOURCE_FIELD_NAME_INTERNAL))
            {
                SPField sourceField = list.Fields.GetField(CONST.SOURCE_FIELD_NAME_INTERNAL);
                sourceField.Description = "(Internal name.)";
                sourceField.Update();
            }
            if (list.Fields.ContainsField(CONST.TARGET_LIST_NAME))
            {
                SPField sourceField = list.Fields.GetField(CONST.TARGET_LIST_NAME);
                sourceField.Description = "(Name or GUID.)";
                sourceField.Update();
            }
            if (list.Fields.ContainsField(CONST.TARGET_FIELD_NAME))
            {
                SPField sourceField = list.Fields.GetField(CONST.TARGET_FIELD_NAME);
                sourceField.Description = "(Display or internal name.)";
                sourceField.Update();
            }

            foreach (string hiddenItem in new string[] { CONST.SOURCE_WEB_URL, CONST.SOURCE_LIST_GUID, CONST.TARGET_LIST_GUID })
                if (list.Fields.ContainsField(hiddenItem))
                {
                    SPField field = list.Fields.GetField(hiddenItem);
                    if (field.CanToggleHidden)
                        field.Hidden = true;
                    else
                    {
                        field.ShowInDisplayForm = false;
                        field.ShowInEditForm = false;
                        field.ShowInNewForm = false;

                    }
                    field.Update();

                }

            if (list.Fields.ContainsField("Title"))
            {
                SPField field = list.Fields.GetField("Title");
                field.Title = "Description";
                field.Required = false;
                field.Update();
            }
            #endregion
            addEventHandler(list);
            list.Hidden = true;
            list.Update();
            return list;
        }
        private void addEventHandler(SPList list)
        {
            const string className = "SP_Form_Suggestion.ConfigListEventReceiver.ConfigListEventReceiver";
            string assembly = System.Reflection.Assembly.GetExecutingAssembly().FullName;
            list.EventReceivers.Add(SPEventReceiverType.ItemAdding, assembly, className);
            list.EventReceivers.Add(SPEventReceiverType.ItemUpdating, assembly, className);
            list.EventReceivers.Add(SPEventReceiverType.ItemDeleting, assembly, className);
            list.Update();
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPWeb web = properties.Feature.Parent as SPWeb;
            try
            {
               SPList configList = web.Lists[CONST.CONFIG_LIST_NAME];
                    
                BatchDeleteAllListItems(configList,web);
            
            }
            catch (Exception ex)
            { }
              

        }
        private void BatchDeleteAllListItems(SPList List,SPWeb web)
        {
           System.Text.StringBuilder builder = new System.Text.StringBuilder();
            builder.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");

            foreach (SPListItem item in List.Items)
            {
                builder.Append("<Method OnError=\"Continue\">");
                builder.Append("<SetList Scope=\"Request\">" + List.ID.ToString() + "</SetList>");
                builder.Append("<SetVar Name=\"ID\">" + item.ID.ToString() + "</SetVar>");
                builder.Append("<SetVar Name=\"Cmd\">Delete</SetVar>");
                builder.Append("</Method>");
            }
            builder.Append("</Batch>");

            try
            {
                web.ProcessBatchData(builder.ToString());
            }
            catch (Exception ex)
            {
               
            }
      
        }
        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
            SPWeb web = properties.Feature.Parent as SPWeb;
            try
            {
                web.DeleteProperty(CONST.PROPERTY_BAG_JQUERY_UI_CSS_URL);
                web.DeleteProperty(CONST.PROPERTY_BAG_JQUERY_UI_URL);
                web.DeleteProperty(CONST.PROPERTY_BAG_JQUERY_URL);
                web.Update();
            }
            catch (Exception ex)
            { }
            try
            {
                
                SPList list = web.Lists[CONST.CONFIG_LIST_NAME];
                BatchDeleteAllListItems(list, web);
                list.Delete();
                web.Update();
            }
            catch (Exception ex)
            { }
        }


    }
}
